<?php

namespace app\modules\api\controllers;

use Yii;
use yii\web\Controller;
use common\models\Tools;
use common\models\Category;
use common\models\CateAttr;
use common\models\CateAttrVal;
use common\models\Goods;

/**
 * Default controller for the `api` module
 */
class PublishController extends Controller
{
    public $enableCsrfValidation = false;
    
    /***
     * 获取下级分类
     */
    public function actionGetsubcate(){
        $cate_id = Tools::GetSafeParam('cate_id', 0, 0);
        $data = Category::getSubCate($cate_id);
        $output = [];
        $output['data'] = $data;
        $output['msg'] = "获取成功！";
        Tools::outputjson($output);
    }
    
    /***
     * url:/api/publish/get-attr
     */
    public function actionGetAttr(){
        $cate_id = Tools::GetSafeParam('cate_id', 0, 0);
        $data = CateAttr::getAttrlistByCate($cate_id);
        foreach($data as $key=>$value){
            if($value['type']==1 || $value['type']==2){
                $data[$key]['optional'] = CateAttrVal::getCateAttrValByAttrId($value['id']);
                $test = $value['id'];
            }
        }
        $output = [];
        $output['data'] = $data;
        $output['msg'] = "获取成功！";
        Tools::outputjson($output);
    }
    
    function base64_image_content($base64_image_content,$path){
       
        //匹配出图片的格式
        $imgroot = rand(1, 999);
        $imgname_tag = rand(10000, 99999);
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            $type = $result[2];
            $new_file = $path."/".date('Y-m-d',time())."/".$imgroot."/";
            
            \app\components\FileUpload::mkDirIfNotExist($new_file);
            
            $new_file = $new_file.time().$imgname_tag.".".$type;
            
            $base64_string= explode(',', $base64_image_content); //截取data:image/png;base64, 这个逗号后的字符
            $data= base64_decode($base64_string[1]);
            
            
            if (file_put_contents($new_file, $data)){
                return $new_file;
            }else{
                return "";
            }
        }else{
            return "";
        }
    }
    
    /***
     * 商品图片上传
     */
    public function actionGoodsimgupload(){
        $imgdata = Tools::GetSafeParam('imgdata', "", 1);
        
        $path = Yii::$app->params['goodsimg'];
        $data_url = $this->base64_image_content($imgdata, $path);
        $data_url = substr($data_url, 1, strlen($data_url));
        
        $data['success'] = 1;
        $data['msg'] = "上传成功！";
        $data['url'] = $data_url;
        \common\models\Tools::outputjson($data);
        
//        $url = Yii::$app->params['img_server'].'/upload/goodsimgupload';
//        $param = ['imgdata'=>$imgdata];
//        $request_result = Tools::curl_post_https($url, $param);
//        print_r($request_result);exit;
        
        
        
//        $output_result = [];
//        $goodsimg = $type = $_FILES["goodsimg"];
//        if(empty($goodsimg)){
//            $data['success'] = 0;
//            $data['msg'] = "数据错误！";
//            \common\models\Tools::outputjson($data);
//        }
//        $imgroot = rand(1, 999);
//        $date = date("Y-m-d");
//        foreach($goodsimg['size'] as $size_key=>$size_val){
//            if($size_val > 10*1024*1024){//最大上传10M的图片
//                $data['success'] = 0;
//                $data['msg'] = "单个文件不能超过10M，请先压缩一下";
//                \common\models\Tools::outputjson($data);
//            }
//            
//            if ($goodsimg['type'][$size_key] != "image/gif" && $goodsimg['type'][$size_key] != "image/jpeg" && $goodsimg['type'][$size_key] != "image/pjpeg"){
//                $data['success'] = 0;
//                $data['msg'] = "格式不对，请上传正常格式的图片";
//                \common\models\Tools::outputjson($data);
//            }
//            $tmpName = $goodsimg['tmp_name'][$size_key];
//            $fileName = $goodsimg['name'][$size_key];
//            $extName = substr($fileName, strlen($fileName) - 3);
//            
//            $path = Yii::$app->params['goodsimg'] ."/" . $date. "/" . $imgroot;
//            $path = $path . "/";
//            //目录不存在的话，创建一个
//            \app\components\FileUpload::mkDirIfNotExist($path);
//            //要保存到服务器上的文件名
//            $result = $path . md5_file($tmpName) . "." . $extName;
//            //上传文件，确保文件唯一性
//            if (!file_exists($result)) {
//                move_uploaded_file($tmpName, $result);
//            }
//            //去掉前面的".",保存到数据库中的信息
//            $result = substr($result, 1, strlen($result));
//            
//            $url = Yii::$app->params['img_server'].'/upload/goodsimgupload';
//            
//            
//            
//            
//            $database64 = self::imgToBase64($result);
//            
//            $param = 'file='.$database64;
//            $request_result = Tools::requestPost($url, $param);
//            
//            array_push($output_result,$request_result);
//        }
//        
//        $data['success'] = 1;
//        $data['urls'] = $output_result;
//        \common\models\Tools::outputjson($data);
    }
    
    public function actionSave(){
        //登录检测
        if (Yii::$app->user->isGuest) {
            $output['success'] = 0;
            $output['msg'] = '未登录，请先登录！';
            Tools::outputjson($output);
        }
        $user = [];
        $user['userid'] = Yii::$app->user->identity->id;
        $user['username'] = Yii::$app->user->identity->username;
        $user['region_1'] = Yii::$app->user->identity->region_1;
        $user['region_2'] = Yii::$app->user->identity->region_2;
        $user['region_3'] = Yii::$app->user->identity->region_3;
        //Array ( [first_cate] => 1 [second_cate] => 2 [third_cate] => 18 [goodsname] => 广告位1 [price] => 1000 [is_tall] => 0 [order_endtime] => 2020-06-18 [attr_5] => 1 [attr_6] => 50 [attr_7] => 20 [attr_8] => 24 [goodsimg_0] => /goodsimg/2020-06-18/95/159246467443328.jpeg [goodsimg_1] => /goodsimg/2020-06-18/23/159246467687944.jpeg )
        
        $goods_info = Goods::goodsSaveCheck();
        
        $save = Goods::goodsSave($user,$goods_info);
        if($save){
            $output['success'] = 1;
            $output['msg'] = '发布成功！';
            Tools::outputjson($output);
        }
    }
    
    public function actionUpdatesave(){
        //登录检测
        if (Yii::$app->user->isGuest) {
            $output['success'] = 0;
            $output['msg'] = '未登录，请先登录！';
            Tools::outputjson($output);
        }
        $user = [];
        $user['userid'] = Yii::$app->user->identity->id;
        $user['username'] = Yii::$app->user->identity->username;
        
        
        $save = Goods::goodsUpdateSave($user);
        if($save){
            $output['success'] = 1;
            $output['msg'] = '修改成功！';
            Tools::outputjson($output);
        }
    }
}
